import axios from "axios"
import router from "../router";
import { ElMessage } from "element-plus";
import { getToken } from "@/utils/loginStateUtil";

const service = axios.create({
    //使用Node的环境变量完成BASEURL的处理
    baseURL: process.env.VUE_APP_BASE_URL,
    timeout: 10000
})

//不参与过滤的接口	
const notFilterApi = [
    "/admin/login/pwd",
    "/admin/login/code",
    "/sms/send",
]

//请求拦截器
service.interceptors.request.use((config)=>{
    //console.log(`output->`,config)
    
    //不参与过滤的接口直接放过
    if(notFilterApi.includes(config.url)){
        return config
    }

    const token = getToken()
    if(token){
        config.headers.token=token;
        return config
    }

    router.push("/user/login")
    ElMessage.error("用户登录状态异常")
    return Promise.reject(error)

},(error)=>{
    ElMessage.error("未知异常")
    return Promise.reject(error)
})

//响应拦截器
service.interceptors.response.use(response=>{
    if(response.status ==200){
        return Promise.resolve(response)
    }else{
        ElMessage.error("未知异常")
        return Promise.reject(response)
    }
},error=>{
    return Promise.reject(error)
})

//请求类
class Req{
    static async get(path,params){
        return service.get(path,{params})
    }

    static async post(path,params){
        let data = new FormData()
        if(params){
            for(let key in params){
                data.append(key,params[key])
            }
        }
        return service.post(path,data) 
    }
}

export{
    Req as req
}